package com.auto.learning.pay.wechatpay;

import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Xml;

import com.auto.learning.R;
import com.auto.learning.tools.MD5;
import com.auto.learning.tools.Util;
import com.tencent.mm.sdk.modelmsg.GetMessageFromWX.Req;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * 微信支付
 * @author wangjianjun
 */
public class WechatPayCommon {
	
	public static int payMoney = 0;
	
	private Context context;
	IWXAPI msgApi ;
	int money;
	
	public WechatPayCommon(Context context, int money) {
		this.context = context;
		this.money = money;
		payMoney = money;
		msgApi= WXAPIFactory.createWXAPI(context, null);
	}

	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	
	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}
	
	private String genOutTradNo() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}

	
	private StringBuffer sb = new StringBuffer();
	private Map<String, String> resultunifiedorder;
	
	public void registerApp(){
		msgApi.registerApp(Constants.APP_ID);	
	}
	
	public void sendPayInfo(){
		PayReq resquest = new PayReq();
		resquest.appId = Constants.APP_ID;
		resquest.partnerId = Constants.MCH_ID;
		resquest.prepayId = resultunifiedorder.get("prepay_id");
		resquest.packageValue = "Sign=WXPay";
		resquest.nonceStr = genNonceStr();
		resquest.timeStamp = String.valueOf(genTimeStamp());
		
		
		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", resquest.appId));
		signParams.add(new BasicNameValuePair("noncestr", resquest.nonceStr));
		signParams.add(new BasicNameValuePair("package", resquest.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", resquest.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", resquest.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", resquest.timeStamp));
		resquest.sign = genAppSign(signParams);
		msgApi.registerApp(Constants.APP_ID);
		msgApi.sendReq(resquest);
	}
	
	/**
	 * app端生成的预支付订单号
	 * @param numMoney
	 */
	public void executePayTask(int numMoney){
		GetPrepayIdTask getPrepayIdTask = new GetPrepayIdTask();
		getPrepayIdTask.execute(numMoney);
	}
	
	public void payByWeixin(String prepareId){
		resultunifiedorder = new HashMap<String, String>();
		resultunifiedorder.put("prepay_id", prepareId);
		sendPayInfo();
	}
	
	/**
	 * 客户端生产订单
	 * @author wangjianjun
	 */
	public class GetPrepayIdTask extends AsyncTask<Integer, Void, Map<String,String>> {

		public ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(context, context.getString(R.string.app_tip), context.getString(R.string.getting_prepayid));
		}

		@Override
		protected void onPostExecute(Map<String,String> result) {
			if (dialog != null) {
				dialog.dismiss();
			}
			resultunifiedorder = result;
			sendPayInfo();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Map<String,String>  doInBackground(Integer... params) {

			String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			String entity = genProductArgs(params[0]*100);
			byte[] buf = Util.httpPost(url, entity);
			String content = new String(buf);
			Log.e("orion", content);
			Map<String,String> xml=decodeXml(content);
			return xml;
		}
	}
	
	public Map<String,String> decodeXml(String content) {

		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName=parser.getName();
				switch (event) {
					case XmlPullParser.START_DOCUMENT:

						break;
					case XmlPullParser.START_TAG:

						if("xml".equals(nodeName)==false){
							xml.put(nodeName,parser.nextText());
						}
						break;
					case XmlPullParser.END_TAG:
						break;
				}
				event = parser.next();
			}

			return xml;
		} catch (Exception e) {
			Log.e("orion",e.toString());
		}
		return null;

	}
	
	private String genProductArgs(int numMoney) {
		StringBuffer xml = new StringBuffer();

		try {
			String	nonceStr = genNonceStr();
			xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
			packageParams.add(new BasicNameValuePair("body", "WeChat-Pay"));
			packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams.add(new BasicNameValuePair("notify_url", "http://www.auto-learning.com"));
			packageParams.add(new BasicNameValuePair("out_trade_no",genOutTradNo()));
//			packageParams.add(new BasicNameValuePair("spbill_create_ip","127.0.0.1"));
			packageParams.add(new BasicNameValuePair("total_fee", String.valueOf(numMoney)));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));

			String sign = genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));
		    String xmlstring = toXml(packageParams);
			return xmlstring;
		} catch (Exception e) {
			return null;
		}
	}
	
	
	 public String changeCharset(String str, String newCharset)  throws UnsupportedEncodingException {
		  if (str != null) {
		   //用默认字符编码解码字符串。
		   byte[] bs = str.getBytes();
		   //用新的字符编码生成字符串
		   return new String(bs, newCharset);
		  }
		  return null;
	}
	
	/**
	 生成签名
	 */
	private String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);
		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",packageSign);
		return packageSign;
	}
	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

       this.sb.append("sign str\n"+sb.toString()+"\n\n");
		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",appSign);
		return appSign;
	}
	
	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<"+params.get(i).getName()+">");
			sb.append(params.get(i).getValue());
			sb.append("</"+params.get(i).getName()+">");
		}
		sb.append("</xml>");
		Log.e("orion",sb.toString());
		return sb.toString();
	}
}
